<script setup lang='ts'>
import type { FieldValues } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useDelCategory, useDelCategoryAttribute, useGetCategoryTree, useGetProductCategory } from '@fl/api/mall-api'
import { SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

import AddOrEdit from './add-or-edit.vue'
import AddOrEditAttribute from './add-or-edit-attribute.vue'

const visible = ref<boolean>(false)
const attributeVisible = ref<boolean>(false)
const initialState = {
    categoryId: 0,

}

const state = ref<FieldValues>(cloneDeep(initialState))
const currentCategoryId = ref<number>(0)
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const records = ref()
const id = ref<string>('')
const parentId = ref<number>(0)
const attributeId = ref<string>('')
const type = ref<string>('')
const attributeDialogType = ref<string>('')

const { createConfirmModal, createMessage } = useMessage()
const { data: treeData } = useGetCategoryTree()
const { mutate: delCategoryMutate } = useDelCategory()
const { mutate: delCategoryAttributeMutate } = useDelCategoryAttribute()
const params = computed(() => ({
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
    ...state.value,
}))

const { data: tableData, isLoading, refetch } = useGetProductCategory(params)

watchEffect(() => {
    if (tableData.value) {
        records.value = cloneDeep(tableData.value)
        // tablePage.value.total = tableData.value.total ?? 0
    }
})

const defaultProps = {
    children: 'children',
    label: 'categoryName',
}

const gridOptions = reactive<VxeGridProps>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { field: 'id', title: '属性ID' },
        { field: 'attributeName', title: '属性名称' },
        { field: 'attributeValue', slots: { default: 'attributeValue' }, title: '属性值' },
        { slots: { default: 'operate' }, title: '操作' },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 500,
    keepSource: true,
    showOverflow: true,
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

function look(categoryId: any) {
    id.value = categoryId
    type.value = 'view'
    visible.value = true
}

function edit(categoryId: any) {
    id.value = categoryId
    visible.value = true
}

function del(ids: string) {
    createConfirmModal({ content: '是否确认删除？', onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        delCategoryMutate(ids, {
            onSuccess: () => {
                parentId.value = 0
                ElMessage.success('删除成功')
            },
        })
    } })
}

function handleNodeClick(data: any) {
    console.log(data, 'data')
    parentId.value = data.id
    currentCategoryId.value = data.id
    state.value.categoryId = data.id
    refetch()
}

function lookAttribute(id: string) {
    attributeId.value = id
    attributeDialogType.value = 'view'
    attributeVisible.value = true
}

function addAttribute() {
    if (!currentCategoryId.value) {
        createMessage.warning('请选择产品类目')
        return
    }
    attributeDialogType.value = 'add'
    attributeVisible.value = true
}

function editAttribute(id: string) {
    attributeId.value = id
    attributeDialogType.value = 'edit'
    attributeVisible.value = true
}

function delAttribute(attributeId: string) {
    createConfirmModal({ content: '是否确认删除？', onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        delCategoryAttributeMutate(attributeId, {
            onSuccess: () => {
                ElMessage.success('删除成功')
                refetch()
            },
        })
    } })
}

function getAttributeValue(attributeValue: string) {
    if (JSON.parse(attributeValue).length) {
        return JSON.parse(attributeValue).map((item: any) => item.value).join(',')
    }
}
</script>

<template>
    <div class="category-wrap">
        <div class="left">
            <div class="tree-wrap">
                <el-tree :data="treeData"
                         class="py-10 pl-10 pr-15"
                         node-key="id"
                         highlight-current
                         default-expand-all
                         :props="defaultProps"
                         :expand-on-click-node="false"
                         @node-click="handleNodeClick"
                >
                    <template #default="{ node, data }">
                        <span class="custom-tree-node">
                            <span>{{ node.label }}</span>

                            <span v-if="currentCategoryId === data.id">
                                <a class="ml-8 text-gray-700"
                                   @click="look(data.id)"
                                >
                                    <el-icon>
                                        <View />
                                    </el-icon>
                                </a>

                                <a class="ml-8 text-gray-700"
                                   @click="edit(data.id)"
                                >
                                    <el-icon><Edit /></el-icon>
                                </a>

                                <a class="ml-8 text-gray-700"
                                   @click="del(data.id)"
                                >
                                    <el-icon><Delete /></el-icon>
                                </a>
                            </span>
                        </span>
                    </template>
                </el-tree>
            </div>

            <div class="mt-10 bg-blue-500 text-white flex h-30 w-full cursor-pointer justify-center items-center"
                 @click="visible = true"
            >
                新建类目
            </div>
        </div>

        <div class="right">
            <ElCard shadow="never">
                <SearchTable v-bind="gridOptions"
                             row-class-name="table-row-style"
                             :loading="isLoading"
                             :data="records"
                >
                    <template #toolbar_buttons>
                        <div class="w-full">
                            <el-row>
                                <el-col :span="12">
                                    <ElButton type="primary"
                                              @click="addAttribute()"
                                    >
                                        新建属性
                                    </ElButton>

                                    <!-- <ElButton type="primary"
                                              @click="delttribute()"
                                    >
                                        删除
                                    </ElButton>

                                    <ElButton type="primary">
                                        导入
                                    </ElButton> -->
                                </el-col>
                            </el-row>
                        </div>
                    </template>

                    <template #attributeValue="{ row }">
                        {{ getAttributeValue(row.attributeValue) }}
                    </template>

                    <template #operate="{ row }">
                        <el-space>
                            <div class="text-blue-400">
                                <span class="cursor-pointer"
                                      @click="lookAttribute(row.id)"
                                >
                                    查看
                                </span>

                                <span class="cursor-pointer"
                                      @click="editAttribute(row.id)"
                                >
                                    编辑
                                </span>

                                <span class="cursor-pointer"
                                      @click="delAttribute(row.id)"
                                >
                                    删除
                                </span>
                            </div>
                        </el-space>
                    </template>
                </SearchTable>
            </ElCard>
        </div>
    </div>

    <AddOrEdit :key="id"
               v-model:parentId="parentId"
               v-model:type="type"
               v-model:visible="visible"
               v-model:id="id"
    />

    <AddOrEditAttribute :key="currentCategoryId"
                        v-model:attributeId="attributeId"
                        v-model:attributeVisible="attributeVisible"
                        v-model:currentCategoryId="currentCategoryId"
                        v-model:attributeDialogType="attributeDialogType"
                        @success="refetch"
    />
</template>

<style scoped lang='less'>
.category-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    overflow: hidden;

    .left {
        width: max-content;
        min-width: 288px;
        margin-right: 10px;
        background-color: #fff;
        overflow: hidden;
        .tree-wrap {
            width: 100%;
            height: 720px;
            overflow-y: auto;
        }
    }

    .right {
        flex: 1;
        background-color: #fff;
        overflow: hidden;
    }
}
</style>
